package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.constant.OtherConstant;
import com.hmdp.constant.RedisConstant;
import com.hmdp.constant.StatusConstant;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 發送短信驗證碼
     *
     * @param phone
     * @param session
     * @return
     */
    public Result sendCode(String phone, HttpSession session) {
        // 校验手机号码是否合法
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail(StatusConstant.PHONE_FORMAT_ERROR);
        }

        // 生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 保存验证码到redis中
//        session.setAttribute(OtherConstant.CODE, code);
        stringRedisTemplate.opsForValue().set(RedisConstant.LOGIN_CODE + phone , code, 120, TimeUnit.SECONDS);
        log.debug("验证码：{}", code);

        return Result.ok();
    }

    /**
     * 登入
     *
     * @param loginForm
     * @param session
     * @return
     */
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //校驗手機號
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail(StatusConstant.PHONE_FORMAT_ERROR);
        }

        //校驗驗證碼
//        String code = (String) session.getAttribute(OtherConstant.CODE);
        String phone = loginForm.getPhone();
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstant.LOGIN_CODE + phone);
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.equals(code)) {
            return Result.fail(StatusConstant.CODE_ERROR);
        }

        User user = query().eq(OtherConstant.PHONE, phone).one();

        //不存在,創建用戶,保存用戶到session
        if (user == null) {
            user = createUserWithPhone(phone);
        }
//        UserDTO userDTO = new UserDTO();
//        BeanUtils.copyProperties(user, userDTO);
//        session.setAttribute(OtherConstant.USER_DTO, userDTO);

        // 保存用戶到redis中


        // 隨機生成token,作爲登錄令牌
        String token = UUID.randomUUID().toString();

        //  將User對象轉爲Hash存儲
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        //  將token存儲到redis中
        String tokenKey =RedisConstant.LOGIN_TOKEN+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        stringRedisTemplate.expire(tokenKey, 30, TimeUnit.MINUTES);

        //  返回token
        return Result.ok(token);
    }

    /**
     * 根據手機號創建用戶
     *
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setNickName(OtherConstant.DEFAULT_NICK_NAME + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
